package com.kexio.auth.util;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;

/**
 * 客户端 IP 工具
 *
 * - 优先从代理头部解析：X-Forwarded-For, X-Real-IP, X-Original-Forwarded-For
 * - 回退到 request.getRemoteAddr()
 * - 仅做基础实现，可信代理链与白名单可后续通过配置扩展
 */
public final class IpUtils {

    private IpUtils() {}

    public static String getClientIp(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }

        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.hasText(xForwardedFor)) {
            // 取第一个非空、非 unknown 的 IP
            String[] parts = xForwardedFor.split(",");
            for (String part : parts) {
                String ip = part.trim();
                if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                }
            }
        }

        String xRealIP = request.getHeader("X-Real-IP");
        if (StringUtils.hasText(xRealIP) && !"unknown".equalsIgnoreCase(xRealIP)) {
            return xRealIP;
        }

        String xOriginalForwardedFor = request.getHeader("X-Original-Forwarded-For");
        if (StringUtils.hasText(xOriginalForwardedFor)) {
            String[] parts = xOriginalForwardedFor.split(",");
            for (String part : parts) {
                String ip = part.trim();
                if (StringUtils.hasText(ip) && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                }
            }
        }

        return request.getRemoteAddr();
    }
}


